package com.winz.cultureapp.http;

import com.winz.cultureapp.http.restful.RetrofitProvider;
import com.winz.cultureapp.utils.JsonUtil;
import com.winz.cultureapp.utils.Logger;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

public class DownloadUtils{
    private static final String TAG = "DownloadUtils";

    private OnFinishedListener listener;



    public static DownloadUtils getInstance(){

        return new DownloadUtils();
    }
    /**
     * 开始下载
     * @param url
     * @param file
     */
    public void download(@NonNull String url, final File file,OnFinishedListener listener) {
        this.listener  = listener;

        RetrofitProvider.Factory.getApiService().download(url)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RetrofitUtil<ResponseBody>().setOnResponeListener(new OnResponeListener<ResponseBody>() {
                    @Override
                    public void onSuccess(ResponseBody bean) {
                        writeFile(bean.byteStream(), file);
                        Logger.d(TAG, JsonUtil.getJsonFromObj(bean));

                    }

                    @Override
                    public void onFailed(String error) {

                    }
                }));

    }

    /**
     * 将输入流写入文件
     * @param inputString
     * @param file
     */
    private void writeFile(InputStream inputString, File file) {
        if (file.exists()) {
            file.delete();
        }

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);

            byte[] b = new byte[1024];

            int len;
            while ((len = inputString.read(b)) != -1) {
                fos.write(b,0,len);
            }
            Logger.d(TAG, "success" + file.getPath());
            if (listener != null){
                listener.onFinished(file.getPath());
            }
            inputString.close();
            fos.close();

        } catch (FileNotFoundException e) {
            if (listener != null){
                listener.onFailed(e.getLocalizedMessage());
            }
            Logger.d(TAG, "FileNotFoundException");
        } catch (IOException e) {
            if (listener != null){
                listener.onFailed(e.getLocalizedMessage());
            }
            Logger.d(TAG, "IOException");
        }
    }

    public interface OnFinishedListener{
        void onFinished(String filePath);
        void onFailed(String error);
    }

}